package fr.labri.macchiato.server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;

/**
 * Executes a Sparql Query on a local model
 * 
 * @author Paul SARRAUTE
 *
 */
public class JenaQueryLauncher {

	private static JenaQueryLauncher instance = null;

	private Model model;

	private JenaQueryLauncher() {
		System.out.println("Model loading...");
		try {			
			InputStream in = new FileInputStream(new File("Macchiato.n3"));
			model = ModelFactory.createMemModelMaker().createModel("Model");
			model.read(in, null, "N3");
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Model loaded!");
	}

	/**
	 * @return the single instance of the class
	 */
	public static JenaQueryLauncher getInstance() {
		if (instance == null)
			instance = new JenaQueryLauncher();
		return instance;
	}

	private ResultSet launchQueryAux(String queryString) {
		Query query = QueryFactory.create(queryString);

		QueryExecution qe = QueryExecutionFactory.create(query, model);
		return qe.execSelect();
	}
	
	/**
	 * Executes a Sparql query and return a JSON result
	 * @param queryString
	 * @return a JSON result of the query
	 */
	public String launchQueryForJSON(String queryString) {
		ResultSet results = launchQueryAux(queryString);
		
		OutputStream out = new ByteArrayOutputStream();
		ResultSetFormatter.outputAsJSON(out, results);
		
		System.out.println(out);
		return out.toString();
	}
	

}
